<?php

namespace app\admin\service;

use app\common\model\commonModel;
use app\common\model\trDriver;
use app\common\model\trInvoices;
use app\common\model\trUser;
use app\common\util\ErrorCode;
use think\Db;

/**
 * Class Auth
 * @package app\admin\service
 * 用户服务类
 */
class UserService
{
    private $returnData;
    private $field = [
        "nickname" => "require", "gender" => "1", "mobile" => "require", "email" => "", "avatar" => "",
        "address" => "", "remark" => "", "status" => "require", "user_type" => 0
    ]; //填入数据库需要存储的表字段
    private $data = [];
    private $mall_id = 0;
    private $params;

    public function __construct($data, $params = [])
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    //分页列表
    public function getList()
    {
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        $filter = array(["mall_id", "=", $this->mall_id]);
        if(!empty($this->params['search'])){
            if(is_numeric($this->params['search'])){
                $filter[] = ['mobile', 'like', "%{$this->params["search"]}%"];
            }else {
                $filter[] = ['nickname', 'like', "%".$this->params["search"] . "%"];
            }
        }
        if(!empty($this->params['timeFrom']) && !empty($this->params['timeTo'])){
            $filter[] = ['register_time', 'between', [strtotime($this->params['timeFrom']), strtotime($this->params['timeTo'])]];
        }
        $model = new trUser();
        $data = $model->getList("id,number_id,avatar,nickname,gender,mobile,email,register_time,status,amount", $filter, $page, $pageSize);
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            foreach ($data["data"] as $k => $item){
                $data["data"][$k]["couponCount"] = commonModel::getCount(userCouponTable, [["user_id", "=", $item["id"]], ["status", '=', "1"], ["end_time", ">=", time()]]);
            }
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    public function getAll(){
        $model = new trUser();
        $data = $model->getFields("id,nickname", ["status" => 1, "mall_id" => $this->mall_id], false);
        $this->returnData['data'] = $data;
        return $this->returnData;
    }

    //客户信息
    public function getDetail(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trUser();
        $field = "number_id,nickname,gender,avatar,status,mobile,email,address,balance,openid,amount,register_time,remark,user_type";
        $data = $model->getFields($field, ["id" => $this->params['id'], "mall_id" => $this->mall_id]);
        if(!empty($data)) {
            $data["userType"] = intval($data["userType"]);
            $data["couponCount"] = commonModel::getCount(userCouponTable, [["user_id", "=", $this->params["id"]], ["status", '=', "1"], ["end_time", ">=", time()]]); //卡券数
            $data["useCouponCount"] = commonModel::getCount(userCouponTable, [["user_id", "=", $this->params['id']], ["status", '=', "2"]]); //已使用的卡券数
            $invoiceModel = new trInvoices();
            $data["invoiceCount"] = $invoiceModel->getCount(["user_id" => $this->params["id"], "status" => 2]); //已开的发票量
            $recentConsumptionTime = \db()->name("order")
                ->where("user_id", $this->params["id"])
                ->where("status", "<>", "1")
                ->where("status", "<>", "3")
                ->order("id desc")
                ->limit(0, 1)
                ->value("create_time");//最近消费时间
            $data["recentConsumptionTime"] = $recentConsumptionTime ? date("Y-m-d H:i:s", $recentConsumptionTime) : "0";
            if ($data["userType"] == "1") {
                $driverModel = new trDriver();
                $driverData = $driverModel->getFields("id as driverId", Db::raw('openid = "' . $data["openid"] . '"'), true, false); // 曾经绑定过司机了
                $data["driverId"] = isset($driverData["driverId"]) ? $driverData["driverId"] : 0;
            }
        }
        $this->returnData['data'] = $data;
        return $this->returnData;
    }

    // 添加
    public function toAdd()
    {
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                return ErrorCode::code("params_not_exist", $ks);
            }
            $this->data[$k] = isset($this->params[$ks]) ? $this->params[$ks] : $v;
        }
        $this->data["mall_id"] = $this->mall_id;
        $model = new trUser();
        $result = $model->add($this->data);
        if (isset($result["code"])) {
            return $result;
        }
        if (!$result) {
            $this->returnData = ErrorCode::$errorCode["fail"];
        }
        return $this->returnData;
    }

    //更新
    public function toUpdate(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if(isset($this->params[$ks])) {
                $this->data[$k] = $this->params[$ks];
            }
        }
        $model = new trUser();
        $oldData = $model->getFields("openid,user_type", ['id' => $this->params['id'], "mall_id" => $this->mall_id], true, false);
        $isError = 0;
        if($this->data["user_type"] == "1") { //需要改成司机了
            $result = $this->modifyDriver($oldData);
            if(isset($result["code"])){
                return $result;
            }
            if(!$result){
                unset($this->data["user_type"]);
                $isError = 1;
            }
        }elseif($this->data["user_type"] == "2") { //需要改成核销员了
            $result = $this->modifyVerifier($oldData);
            if(isset($result["code"])){
                return $result;
            }
            if(!$result){
                unset($this->data["user_type"]);
                $isError = 2;
            }
        }
        $result = $model->doUpdate($this->data, ['id' => $this->params['id'], "mall_id" => $this->mall_id]);
        if(isset($result["code"])){
            return $result;
        }
        if($result) {
            $this->returnData["data"] = ["isError" => $isError];
            return $this->returnData;
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "更新失败";
            return $this->returnData;
        }
    }

    // 同步修改用户司机身份
    public function modifyDriver($data){
        Db::startTrans();
        // 第一次绑定用手机号，并关联了openid。后面就用openid查关系了
        if($data["userType"] == '2'){ // 目前是核销员，要把核销员的openid去掉，防止下次绑定出现相同的openid
            commonModel::toUpdate(verifierTable, ["openid" => null], ["openid" => $data["openid"]]); // 删除openid
        }
        $driverModel = new trDriver();
        $driverData = $driverModel->getFields("id,openid", ["mobile" => $this->data["mobile"], "mall_id" => $this->mall_id], true, false); // 优先查询手机号的司机
        if(empty($driverData)){
            $driverData = $driverModel->getFields("id", Db::raw('openid = "'.$data["openid"].'"'), true, false); // 曾经绑定过司机了
            if(empty($driverData)) {
                Db::rollback();
                return false;
            }else {
                $res = $driverModel->doUpdate(["mobile" => $this->data["mobile"]], ["id" => $driverData["id"]]); // 司机绑定手机号
                if(isset($res["code"])){
                    Db::rollback();
                    return $res;
                }
            }
        }else{
            $res = $driverModel->doUpdate(["openid" => $data['openid']], ["id" => $driverData["id"]]); // 司机第一次绑定微信
            if(isset($res["code"])){
                Db::rollback();
                return $res;
            }
        }
        Db::commit();
        return true;
    }

    // 同步修改用户核销员身份
    public function modifyVerifier($data){
        Db::startTrans();
        // 第一次绑定用手机号，并关联了openid。后面就用openid查关系了
        if($data["userType"] == '1'){ // 目前是司机，要把司机的openid去掉，防止下次绑定出现相同的openid
            $driverModel = new trDriver();
            $driverModel->doUpdate(["openid" => null], ["openid" => $data["openid"]]); // 删除openid
        }
        $verifierData = commonModel::getFields(verifierTable, "id", ["mobile" => $this->data["mobile"], "mall_id" => $this->mall_id], true, false); // 优先查询手机号的核销员
        if(empty($verifierData["id"])){
            $verifierData = commonModel::getFields(verifierTable, "id", Db::raw('openid = "'.$data["openid"].'"'), true, false); // 曾经绑定过核销员了
            if(empty($verifierData["id"])) {
                Db::rollback();
                return false;
            }else {
                $res = commonModel::toUpdate(verifierTable, ["mobile" => $this->data["mobile"]], ["id" => $verifierData["id"]]); // 核销员绑定手机号
                if(isset($res["code"])){
                    Db::rollback();
                    return $res;
                }
            }
        }else{
            $res = commonModel::toUpdate(verifierTable, ["openid" => $data['openid']], ["id" => $verifierData["id"]]); // 核销员第一次绑定微信
            if(isset($res["code"])){
                Db::rollback();
                return $res;
            }
        }
        Db::commit();
        return true;
    }

    // 更新司机状态
    public function updateStatus(){ // status  '状态：1正常；2锁定；3注销
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        if(!in_array($this->params["status"], [1,2,3])){
            return ErrorCode::code("params_error", "status（1正常；2锁定；3注销）");
        }
        $model = new trUser();
        $res = $model->doUpdate(["status" => $this->params["status"]], ["id" => $this->params['id'], "mall_id" => $this->mall_id]);
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "更新失败";
        }
        return $this->returnData;
    }

    //删除
    public function toDel(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "id");
        }
        $model = new trUser();
        $result = $model->delById($this->params['id']);
        if (!$result) {
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "删除失败";
        }
        return $this->returnData;
    }
}